package org.example.service;

import org.example.entity.Admin;
import org.example.util.DateUtil;

import java.io.*;
import java.util.Date;

/**
 * @author TonySong
 * @date 2025/7/28 0028
 * @time 16:52
 */
public class AdminService implements IAdminService{


    private Admin admin;

    public Admin getAdmin() {
        return admin;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    @Override
    public Admin init() throws IOException, ClassNotFoundException {
        //登录时判断是否存在序列化文件，如果存在则说明已经正确登录过：显示登录次数和时间，并
        if(file.exists()){
            admin = load();
            System.out.println("登录次数："+admin.getCount());
            System.out.println("上次登录时间："+ DateUtil.showDate(admin.getLastTime()));
        }
        return admin;
    }

    @Override
    public Admin login(String username, String password) throws IOException, ClassNotFoundException {
            FileReader reader = new FileReader("admin.properties");
            PROPERTIES.load(reader);
            //todo：输入的账号和密码与Properties的账号和密码进行比较
            String username1 = PROPERTIES.getProperty("username");
            String password1 = PROPERTIES.getProperty("password");
            if(username.equals(username1) && password.equals(password1)){
                admin = new Admin();
                admin.setUsername(username);
                admin.setPassword(password);
                return admin;
            }
        return null;
    }

    @Override
    public void saveAdmin(Admin admin) throws IOException {
        if(admin != null){
            ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream(file));
            admin.setLastTime(new Date());
            admin.setCount(admin.getCount()+1);
            outputStream.writeObject(admin);
            outputStream.close();
        }else{
            System.out.println("admin为空！！");
        }
    }

    @Override
    public Admin load() throws IOException, ClassNotFoundException {
        if(file.exists()){
             ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream(file));
             Admin admin=(Admin)inputStream.readObject();
             inputStream.close();
             return admin;
        }else{
            System.out.println("反序列化文件不存在！操作失败");
        }
        return null;
    }
}
